package cn.homework.dao.impl;

import cn.homework.dao.BackstageCustomerDao;
import cn.homework.domain.Customers;
import cn.homework.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ACT
 */
public class BackstageCustomerDaoImpl implements BackstageCustomerDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Customers> findCustomers() {
        String sql = "select * from customers";
        return template.query(sql, new BeanPropertyRowMapper<>(Customers.class));
    }

    @Override
    public Customers findCustomerByName(String customerName) {
        String sql = "select * from customers where name = ?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<>(Customers.class), customerName);
    }

    @Override
    public void delCustomerByName(String customerName) {
        String sql = "delete from customers where name = ?";
        template.update(sql, customerName);
    }

    @Override
    public List<Customers> queryCustomers(Map<String, String[]> map) {
        String sql = "select * from customers  where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //遍历map
        Set<String> keySet = map.keySet();
        //定义参数的集合
        List<Object> params = new ArrayList<>();
        for (String key : keySet) {
            //排除条件信息
            if ("demand".equals(key)) {
                continue;
            }

            //获取values
            String values = map.get(key)[0];
            //判断是否有值
            if (values != null && !"".equals(values)) {
                //有值
                sb.append(" and " + key + " like ? ");
                params.add("%" + values + "%");
            }
        }
        sql = sb.toString();
        return template.query(sql, new BeanPropertyRowMapper<Customers>(Customers.class), params.toArray());
    }
}
